<?php
include_once 'database/db.php';
include $_SERVER['DOCUMENT_ROOT']."/lib/spyc.php";
class Upload{
    private $filepath; //上传目录
    private $tmpPath;  //PHP文件临时目录
    private $blobNum; //第几个文件块
    private $blobSize; // 分片大小
    private $totalBlobNum; //文件块总数
    private $fileName; //文件名
    private $DB; // mongodb数据库驱动

    public function __construct($tmpPath,$blobNum,$blobSize,$totalBlobNum,$fileName){

        $this->tmpPath =  $tmpPath;
        $this->blobNum =  $blobNum;
        $this->totalBlobNum =$totalBlobNum;
        $this->fileName = $fileName;
        $this->blobSize = $blobSize;
        $this->DB = new DB();
        $ENV = spyc_load_file($_SERVER['DOCUMENT_ROOT'].'/properties/env.yml');
        $this->filepath=($ENV['upload']['path'])['0'];

        $this->moveFile();
        $this->fileMerge();
    }

    //判断是否是最后一块，如果是则进行文件合成并且删除文件块
    private function fileMerge(){
        if($this->blobNum == $this->totalBlobNum){
            // 更新数据库中文件信息
            $this->DB->update('fileshare.files',['id'=>sha1($this->fileName)],['lastBlobSize'=>$this->blobSize]);
        }
    }

    //移动文件
    private function moveFile(){
        $this->touchDir();
        $filename = $this->filepath.DIRECTORY_SEPARATOR. $this->fileName.'__'.$this->blobNum;
        move_uploaded_file($this->tmpPath,$filename);
    }

    //API返回数据
    public function apiReturn(){
        $data=[];
        if($this->blobNum == $this->totalBlobNum){
                    $data['code'] = 2;
                    $data['msg'] = 'success';
        }else{
                if(file_exists($this->filepath.DIRECTORY_SEPARATOR. $this->fileName.'__'.$this->blobNum)){
                    $data['code'] = 1;
                    $data['msg'] = 'waiting for all';
                    $data['file_path'] = '';
                    $data['blob_num']=$this->blobNum;
                }
        }
        header('Content-type: application/json');
        echo json_encode($data);
    }

    //建立上传文件夹
    private function touchDir(){
        $this->filepath = $this->filepath.DIRECTORY_SEPARATOR.sha1($this->fileName);
        if(!file_exists($this->filepath)){
            echo "非法上传请求";;
        }
    }
}
//实例化并获取系统变量传参
$upload = new Upload($_FILES['file']['tmp_name'],$_POST['blob_num'],$_POST['blob_size'],$_POST['total_blob_num'],$_POST['file_name']);
//调用方法，返回结果
$upload->apiReturn();
